<script setup lang="ts">
import { onMounted, ref } from 'vue';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import type { CalendarCardDay, FormInstance } from '@nutui/nutui-taro';
import { Edit, Del } from '@nutui/icons-vue-taro';
import { useDateFormat, useNow } from '@vueuse/core';
import type { Receiving } from '@/interface';
import type { Reciprocation } from '@/interface/business/reciprocation';
import { createReciprocation, delReciprocation, listReciprocation, updateReciprocation } from '@/service/api';
import { showErrorMsg } from '@/service/request/helpers';

const receiving = ref<Receiving>({
  id: '',
  bookId: '',
  guestName: '',
  amount: '',
  receiveDate: '',
  remark: '',
  reciprocated: false
});

const reciprocationList = ref<Array<Reciprocation>>([]);

const showCreatePop = ref<boolean>(false);

const reciprocationForm = ref<Reciprocation>({
  id: '',
  bookId: '',
  receivingId: '',
  reciprocateDate: '',
  amount: ''
});

const selectedReciprocateDate = ref<Date>(useNow().value);

const calendarCardShow = ref<boolean>(false);
const onReceiveDateFocus = () => {
  if (!reciprocationForm.value.reciprocateDate) return;
  selectedReciprocateDate.value = new Date(reciprocationForm.value.reciprocateDate);
};

const flushReceivingList = () => {
  const pages = Taro.getCurrentPages();
  const current = pages[pages.length - 1];
  current.getOpenerEventChannel().emit('flushData');
};

const onDayClick = (day: CalendarCardDay) => {
  reciprocationForm.value.reciprocateDate = `${day.year}-${day.month}-${day.date}`;
  calendarCardShow.value = false;
};

const listRec = () => {
  listReciprocation(receiving.value.id)
    .then((res: Service.SuccessResult) => {
      reciprocationList.value = [...res.success];
    })
    .catch((err: Service.RequestError) => {
      Taro.hideLoading();
      showErrorMsg(err.message);
    });
};

const onAdd = () => {
  showCreatePop.value = true;
  selectedReciprocateDate.value = useNow().value;
  reciprocationForm.value.reciprocateDate = useDateFormat(useNow(), 'YYYY-MM-DD').value;
};

const onUpdate = (row: Reciprocation) => {
  showCreatePop.value = true;
  selectedReciprocateDate.value = new Date(row.reciprocateDate);
  reciprocationForm.value.id = row.id;
  reciprocationForm.value.bookId = row.bookId;
  reciprocationForm.value.receivingId = row.receivingId;
  reciprocationForm.value.reciprocateDate = row.reciprocateDate;
  reciprocationForm.value.amount = row.amount;
  reciprocationForm.value.remark = row.remark;
};

const showDeleteDialog = ref<boolean>(false);
const deleteRow = ref<Reciprocation | null>(null);
const onDelete = (row: Reciprocation) => {
  showDeleteDialog.value = true;
  deleteRow.value = row;
};

const onCancel = () => {
  deleteRow.value = null;
  showDeleteDialog.value = false;
};

const onDelConfirm = () => {
  if (deleteRow.value) {
    Taro.showLoading({ title: '删除中...' });
    delReciprocation(deleteRow.value.id)
      .then(() => {
        Taro.hideLoading();
        listRec();
      })
      .catch((err: any) => {
        Taro.hideLoading();
        showErrorMsg(err.message);
      });
  }
};

const formRef = ref<FormInstance>();
const resetForm = () => {
  reciprocationForm.value = {
    id: '',
    bookId: '',
    receivingId: '',
    reciprocateDate: '',
    amount: '',
    remark: ''
  };
  formRef.value?.reset();
};

const onSubmitCancel = () => {
  resetForm();
  showCreatePop.value = false;
};

const onSubmitConfirm = () => {
  formRef.value?.validate().then(res => {
    const { valid, errors } = res as { valid: boolean; errors: Array<object> };
    if (valid) {
      reciprocationForm.value.bookId = receiving.value.bookId;
      reciprocationForm.value.receivingId = receiving.value.id;
      showCreatePop.value = false;
      Taro.showLoading({ title: '保存中...' });
      if (reciprocationForm.value.id) {
        updateReciprocation(reciprocationForm.value)
          .then(() => {
            Taro.hideLoading();
            listRec();
            resetForm();
          })
          .catch((err: Service.RequestError) => {
            Taro.hideLoading();
            showErrorMsg(err.message);
          });
      } else {
        createReciprocation(reciprocationForm.value)
          .then(() => {
            Taro.hideLoading();
            listRec();
            resetForm();
            flushReceivingList();
          })
          .catch((err: Service.RequestError) => {
            Taro.hideLoading();
            showErrorMsg(err.message);
          });
      }
    } else {
      console.log(errors[0]);
      showErrorMsg(`${errors[0]}`);
    }
  });
};

onMounted(() => {
  const pages = Taro.getCurrentPages();
  const current = pages[pages.length - 1];
  current.getOpenerEventChannel().on('initData', (data: Receiving) => {
    receiving.value.id = data.id;
    receiving.value.bookId = data.bookId;
    receiving.value.guestName = data.guestName;
    receiving.value.amount = data.amount;
    receiving.value.receiveDate = data.receiveDate;
    receiving.value.remark = data.remark;
  });
  const { params } = useRouter();
  receiving.value.id = params.receivingId!;
  receiving.value.bookId = params.bookId!;
  listRec();
});
</script>

<template>
  <basic-layout :show-tab-bar="false">
    <custom-nav-bar left-show title="回礼记录" />
    <div class="w-375px text-30px">
      <nut-cell-group class="pt-12px pl-16px pr-16px color-#666">
        <nut-cell center>
          <template #title>
            <span class="text-15px">宾客姓名：{{ receiving.guestName }}</span>
            <span class="text-15px mt-8px">收礼日期：{{ receiving.receiveDate }}</span>
            <span class="text-15px mt-8px">礼金金额：{{ receiving.amount }}</span>
            <span class="text-15px mt-8px">备注信息：{{ receiving.remark }}</span>
          </template>
        </nut-cell>
      </nut-cell-group>
      <nut-steps direction="vertical" :current="0" style="padding: 20px; width: 100%">
        <nut-step @click="onAdd">
          <template #icon>
            <nut-avatar color="#666">+</nut-avatar>
          </template>
          <template #title>
            <span style="color: #666666">点击新增一条回礼记录</span>
          </template>
          <template #content>
            <div style="height: 60px"></div>
          </template>
        </nut-step>
        <nut-step v-for="(item, index) in reciprocationList" :key="index">
          <template #icon>
            <nut-avatar color="#666">回</nut-avatar>
          </template>
          <template #title>
            <span class="reciprocation-title">{{ item.reciprocateDate }} 回礼</span>
          </template>
          <template #content>
            <nut-cell class="step-content-cell" center size="large">
              <template #title>
                <nut-price style="color: #666666" :price="item.amount" :decimal-digits="0" size="large" />
                <span class="cell-remark">{{ item.remark || '--' }}</span>
              </template>
              <template #desc>
                <div class="cell-operation">
                  <nut-space direction="vertical" fill>
                    <nut-button class="operation-btn" type="default" size="small" block @click="onUpdate(item)">
                      <template #icon>
                        <Edit />
                      </template>
                      修改
                    </nut-button>
                    <nut-button class="operation-btn" type="primary" size="small" block @click="onDelete(item)">
                      <template #icon>
                        <Del />
                      </template>
                      删除
                    </nut-button>
                  </nut-space>
                </div>
              </template>
            </nut-cell>
          </template>
        </nut-step>
        <nut-step>
          <template #icon>
            <nut-avatar color="#666">收</nut-avatar>
          </template>
          <template #title>
            <span class="receiving-title">{{ receiving.receiveDate }} 收礼</span>
          </template>
          <template #content>
            <nut-cell class="step-content-cell" center size="large">
              <template #title>
                <nut-price style="color: #666666" :price="receiving.amount" :decimal-digits="0" size="large" />
                <span class="cell-remark">{{ receiving.remark || '--' }}</span>
              </template>
            </nut-cell>
          </template>
        </nut-step>
      </nut-steps>
      <nut-popup
        :visible="calendarCardShow"
        position="bottom"
        safe-area-inset-bottom
        @click-overlay="calendarCardShow = false"
      >
        <nut-calendar-card v-model="selectedReciprocateDate" type="single" @day-click="onDayClick"></nut-calendar-card>
      </nut-popup>
      <nut-popup
        v-model:visible="showCreatePop"
        position="bottom"
        safe-area-inset-bottom
        round
        :style="{ height: '60%' }"
      >
        <template #default>
          <nut-form ref="formRef" star-position="right" :model-value="reciprocationForm" label-position="top">
            <nut-form-item
              label="回礼日期"
              prop="reciprocateDate"
              required
              :rules="[{ required: true, message: '请选择回礼日期' }]"
            >
              <nut-input
                v-model="reciprocationForm.reciprocateDate"
                placeholder=""
                type="text"
                readonly
                :border="false"
                @click="calendarCardShow = true"
                @focus="onReceiveDateFocus"
              />
            </nut-form-item>
            <nut-form-item
              label="回礼礼金"
              prop="amount"
              required
              :rules="[{ required: true, message: '请填写回礼礼金' }]"
            >
              <nut-input v-model="reciprocationForm.amount" placeholder="" type="number" :border="false" />
            </nut-form-item>
            <nut-form-item label="备注信息">
              <textarea
                v-model="reciprocationForm.remark"
                placeholder=" "
                class="bg-#f7f8fa h-100px w-100% b-rd-5px right-4px left-1px"
              />
            </nut-form-item>
          </nut-form>
          <nut-space direction="vertical" fill>
            <nut-button plain block class="hoo-btn hoo-btn--cancel" @click="onSubmitCancel">取消</nut-button>
            <nut-button plain block class="hoo-btn hoo-btn--confirm" @click="onSubmitConfirm">确认</nut-button>
          </nut-space>
        </template>
      </nut-popup>
      <nut-dialog
        v-model:visible="showDeleteDialog"
        title="警告"
        content="数据删除后不能回复，确认是否删除?"
        @cancel="onCancel"
        @ok="onDelConfirm"
      />
    </div>
  </basic-layout>
</template>

<style lang="scss">
@import '@/styles/custom';

.nut-step-main {
  width: 100%;
}

.reciprocation-title {
  //color: #22c3aa;
}
.receiving-title {
  //color: #f44336;
}

.step-content-cell {
  width: 100%;
}

.cell-remark {
  font-size: 12px;
  color: #666666;
  padding: 5px 0 0 5px;
  width: 180px;
}

.cell-operation {
  height: 100%;
  float: right;

  .operation-btn {
    width: 75px;
    //margin: 5px 0;
    border-radius: 5px;
  }
}
</style>
